//
//  AppDelegate.m
//  QCAppProject
//
//  Created by yjl on 2021/8/13.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "QCURL.h"
#import "QCLoginViewController.h"
#import "YFHUtil.h"
#import "QCConsultViewController.h"
#import "QCInformationViewController.h"
#import "QCWebViewController.h"
#import "FDDKeyChain.h"
#import "NSString+Ext.h"
#import "QCNetworkManager.h"
// 引入 JPush 功能所需头文件
#import "JPush/JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define JPUSH_KEY @"a5b2c625d557592fe2db670a"

@interface AppDelegate () <UITabBarControllerDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [QCSingleton instance].URL = [[QCURL alloc] initBaseURL];
    self.tabBarController = [[QCTabBarController alloc] init];
    self.tabBarController.selectedIndex = 0;
    self.tabBarController.delegate = self;
    self.tabBarController.tabBar.translucent = YES;
    [self setTabBarStyle];
    [self handleKeyBord];
    [self saveMD5Random];
    [self initJPushService:launchOptions];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)initJPushService:(NSDictionary *)launchOptions {
    
    //初始化apns代码
    //Required
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        // Fallback on earlier versions
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:JPUSH_KEY
                            channel:@"App Store"
                   apsForProduction:YES
              advertisingIdentifier:nil];
    
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
      if(resCode == 0){
        NSLog(@"registrationID获取成功：%@",registrationID);
          [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:kJpushRegistrationID];
          [[NSUserDefaults standardUserDefaults] synchronize];
          [self loadQueryLinkUrlData];
      } else{
        NSLog(@"registrationID获取失败，code：%d",resCode);
      }
    }];
}

- (void)saveMD5Random {
    if ([YFHUtil isBlankString:[FDDKeyChain getContentFromKeyChain:kMD5RandomKey]]) {
        [FDDKeyChain saveContentToKeyChain:[NSString md5EncryptRandomNumber] forKey:kMD5RandomKey];
    }
}

- (void)setTabBarStyle {
    //线
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -0.5, SCREEN_WIDTH, 0.5)];
    view.backgroundColor = QCOrange;
    [[UITabBar appearance] insertSubview:view atIndex:0];
    //背景色
    [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
//  
    
}

- (UIViewController*)currentViewController{
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (true) {
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        } else if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else {
            break;
        }
    }
    return vc;
}

#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    QCLog(@"%@",[QCSingleton instance].account);
    QCNavigationViewController *navCtrl = (QCNavigationViewController *)viewController;
    UIViewController *rootCtrl = navCtrl.topViewController;
    if([rootCtrl isKindOfClass:[QCConsultViewController class]]) {
        if ([YFHUtil isBlankString:[QCSingleton instance].account] ) {
            [self presentLoginVC];
            return NO;
        }
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
  //    [APService stopLogPageView:@"aa"];
  // Sent when the application is about to move from active to inactive state.
  // This can occur for certain types of temporary interruptions (such as an
  // incoming phone call or SMS message) or when the user quits the application
  // and it begins the transition to the background state.
  // Use this method to pause ongoing tasks, disable timers, and throttle down
  // OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
  // Use this method to release shared resources, save user data, invalidate
  // timers, and store enough application state information to restore your
  // application to its current state in case it is terminated later.
  // If your application supports background execution, this method is called
  // instead of applicationWillTerminate: when the user quits.

  [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
  [application setApplicationIconBadgeNumber:0];
  [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  // Restart any tasks that were paused (or not yet started) while the
  // application was inactive. If the application was previously in the
  // background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
  // Called when the application is about to terminate. Save data if
  // appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - JPUSHRegisterDelegate

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    const unsigned int *tokenBytes = [deviceToken bytes];
    NSString *tokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    NSLog(@"----tokenString-----%@", tokenString);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:
              (void (^)(UIBackgroundFetchResult))completionHandler {
  [JPUSHService handleRemoteNotification:userInfo];
  NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
  
  if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
    
  }
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
    didReceiveLocalNotification:(UILocalNotification *)notification {
}


// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (@available(iOS 10.0, *)) {
        if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //从通知界面直接进入应用
        }else{
            //从通知设置界面进入应用
        }
    } else {
        // Fallback on earlier versions
    }
}


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler  API_AVAILABLE(ios(10.0)){
  NSDictionary * userInfo = notification.request.content.userInfo;
  
  UNNotificationRequest *request = notification.request; // 收到推送的请求
  UNNotificationContent *content = request.content; // 收到推送的消息内容
  
  NSNumber *badge = content.badge;  // 推送消息的角标
  NSString *body = content.body;    // 推送消息体
  UNNotificationSound *sound = content.sound;  // 推送消息的声音
  NSString *subtitle = content.subtitle;  // 推送消息的副标题
  NSString *title = content.title;  // 推送消息的标题
  
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
//      [self pushToViewController:userInfo];
  }
  else {
    // 判断为本地通知
    NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
//      [self pushToViewController:userInfo];
  }
    
    
  completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
  
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  UNNotificationRequest *request = response.notification.request; // 收到推送的请求
  UNNotificationContent *content = request.content; // 收到推送的消息内容
  
  NSNumber *badge = content.badge;  // 推送消息的角标
  NSString *body = content.body;    // 推送消息体
  UNNotificationSound *sound = content.sound;  // 推送消息的声音
  NSString *subtitle = content.subtitle;  // 推送消息的副标题
  NSString *title = content.title;  // 推送消息的标题
  
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [self pushToViewController:userInfo];
      });
  }
  else {
    // 判断为本地通知
    NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [self pushToViewController:userInfo];
      });
  }
  completionHandler();  // 系统要求执行这个方法
}

//- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
//  NSLog(@"receive notification authorization status:%lu, info:%@", status, info);
//}

#endif

//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
//  // Required
//  NSDictionary * userInfo = notification.request.content.userInfo;
//    if (@available(iOS 10.0, *)) {
//        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//            [JPUSHService handleRemoteNotification:userInfo];
//        }
//    } else {
//        // Fallback on earlier versions
//    }
//  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
//}
//
//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler  API_AVAILABLE(ios(10.0)){
//  // Required
//  NSDictionary * userInfo = response.notification.request.content.userInfo;
//    if (@available(iOS 10.0, *)) {
//        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//            [JPUSHService handleRemoteNotification:userInfo];
//        }
//    } else {
//        // Fallback on earlier versions
//    }
//  completionHandler();  // 系统要求执行这个方法
//}
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//
//  // Required, iOS 7 Support
//  [JPUSHService handleRemoteNotification:userInfo];
//  completionHandler(UIBackgroundFetchResultNewData);
//}
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//
//  // Required, For systems with less than or equal to iOS 6
//  [JPUSHService handleRemoteNotification:userInfo];
//}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
  if (![dic count]) {
    return nil;
  }
  NSString *tempStr1 =
      [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                   withString:@"\\U"];
  NSString *tempStr2 =
      [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
  NSString *tempStr3 =
      [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
  NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
  NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
  return str;
}

- (void)pushToViewController:(NSDictionary *)userInfo {
    [JPUSHService setBadge:0];//清空JPush服务器中存储的badge值
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//小红点清0操作
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    app.tabBarController.selectedIndex = 0;
    NSString *pushType = userInfo[@"type"];
    QCNavigationViewController *nav = (QCNavigationViewController *)app.tabBarController.selectedViewController;
    if ([pushType isEqualToString:@"infomation"]) {//公告
        QCInformationViewController *information = [[QCInformationViewController alloc] init];
        [nav pushViewController:information animated:YES];
    } else if ([pushType isEqualToString:@"recharge"]) {//
        QCWebViewController *webVC = [QCWebViewController new];
        webVC.url = [[NSUserDefaults standardUserDefaults] objectForKey:kQueryLinkKey];
        webVC.queryLinkType = QCQueryLinkDefault;
        [nav pushViewController:webVC animated:YES];
    }
}

- (void)presentLoginVC {
    QCLoginViewController *login = [[QCLoginViewController alloc] init];
    login.modalPresentationStyle = UIModalPresentationFullScreen;
    WS(weakSelf)
    login.loginSuccessBlock = ^{
        weakSelf.tabBarController.selectedIndex = 1;
    };
    QCNavigationViewController *nav = [[QCNavigationViewController alloc] initWithRootViewController:login];
    [[self currentViewController] presentViewController:nav animated:YES completion:nil];
}


-(void)handleKeyBord{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = true;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
}

//查询地址接口
- (void)loadQueryLinkUrlData {
    NSString *registrationID = [[NSUserDefaults standardUserDefaults] objectForKey:kJpushRegistrationID];
    NSString *link = [NSString stringWithFormat:@"%@?mchid=%@",[QCSingleton instance].URL.queryLinkUrl,registrationID];
    [QCNetworkManager getRequestWithURL:link parameters:nil Progress:nil success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = responseObject;
            if ([dict.allKeys containsObject:@"data"]) {
                NSDictionary *dict = responseObject[@"data"];
                if (dict && [dict.allKeys containsObject:@"link"]) {
                    NSString *link = dict[@"link"];
                    [[NSUserDefaults standardUserDefaults] setObject:link forKey:kQueryLinkKey];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }
    QCLog(@"=====>>%@",responseObject);
    } failure:^(NSError *error) {
        QCLog(@"=====>>%@",error.description);
    }];
}




@end
